import store from '@/store/index.js'
// {
//   "chatMsgInput": {
//     "accepterId": "string",
//     "msg": "string",
//     "msgId": "string",
//     "senderId": "string"
//   },
//   "extend": "string",
//   "type": 0
// }
export default function (body) {
  const chatMsgInput = body.chatMsgInput
  const sessionList = store.state.sessionList // 从vuex取到sessionList
  const contacts = store.state.contacts // 从vuex取到contacts
  let _index = false
  sessionList.forEach((session, index) => { // 遍历sessionList
    if (session.accepter.friendId === chatMsgInput.senderId) {
      _index = index
    }
  })
  const msg = { // 创建当前消息的对象
    isMyself: false,
    msg: chatMsgInput.msg,
    msgId: chatMsgInput.msgId
  }
  if (_index !== false) { // 如果当前ws接受的会话已存在
    const currentSession = sessionList[_index]
    store.dispatch('updateSessionList', currentSession)
    store.dispatch('getCurrentSession', {currentSession, msg, count: 1}) // 传入msg
    if (store.state.currentSession.accepter.id === currentSession.accepter.id) { // 判断，如果收到的消息就是来自currentSession，则清空count
      store.commit('clearCurrentSessionCount')
    }
  } else { // 当前会话不存在，创建一个会话
    let accepter
    Object.keys(contacts).forEach(title => { // 遍历通讯录，设置当前会话的accepter
      contacts[title].forEach(person => {
        if (person.friendId === chatMsgInput.senderId) {
          accepter = person
        }
      })
    })
    const currentSession = {
      accepter: accepter,
      messages: [msg],
      count: 1
    }
    store.dispatch('updateSessionList', currentSession) // 更新sessionList，push一个会话
  }
}
